package com.xs.ahoi.hcxs.utils;

import android.os.CountDownTimer;
import com.xs.ahoi.hcxs.dao.ConfigDao;
import com.xs.ahoi.hcxs.service.BookFactory;
import com.xs.ahoi.hcxs.utils.tts.TtsUtil;

/**
 * author: ahoi
 * date: 2018/9/26 18:52
 * description: 倒计时工具类
 */
public class TimerDownUtil {

    // 单例对象
    private static TimerDownUtil instance = new TimerDownUtil();
    // 倒计时对象
    private static CountDownTimer countDownTimer;
    // 倒计时回调
    private CallBack callBack;
    // 倒计时秒数
    private static long leaveSecond;

    // 上次点击的按钮下标
    private static int btnArrayIndex;


    public static TimerDownUtil getInstance() {
        return instance;
    }

    public TimerDownUtil() {
        init();
    }

    public void init() {
        btnArrayIndex = -1;
        leaveSecond = -1;
    }

    public void start(long second) {
        cancel();
        countDownTimer = new CountDownTimer(second * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                leaveSecond = millisUntilFinished / 1000;
                callBack.onTick(millisUntilFinished);
            }

            @Override
            public void onFinish() {
                // 只有当正在播放的时候，才会去停止并提示
                if (BookFactory.getInstance().isPlaying()) {
                    BookFactory.getInstance().stopPlay(true);
                    TtsUtil.getInstance().speakText("定时播放结束");
                }
                cancel();
                callBack.onFinish();
                ConfigDao.getInstance().setTimeOver(System.currentTimeMillis());
            }
        }.start();
    }

    public void cancel() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    public void reContinue(long second) {
        start(second);
        setBtnArrayIndex(1);
    }


    //////////////////////////// get set /////////////////////////////////////////////////
    public int getBtnArrayIndex() {
        return btnArrayIndex;
    }

    public void setBtnArrayIndex(int btnArrayIndex) {
        TimerDownUtil.btnArrayIndex = btnArrayIndex;
    }

    public long getLeaveSecond() {
        return leaveSecond;
    }

    public void setCallBack(CallBack callBack) {
        this.callBack = callBack;
    }

    public interface CallBack {
        void onTick(long milliSecond);

        void onFinish();
    }

}
